package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServletMapper {
    private String port;
    private String appBase;
    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    public String getPort() {
        return port;
    }

    public String getAppBase() {
        return appBase;
    }

    public Map<String, HttpServlet> getServletMap() {
        return servletMap;
    }

    public void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            Element connector = (Element) rootElement.selectSingleNode("Service/Connector");
            port = connector.attributeValue("port");

            Element host = (Element) rootElement.selectSingleNode("Service/Engine/Host");
            appBase = host.attributeValue("appBase");
            File appBasePath = new File(appBase);
            if (!appBasePath.exists()) throw new Exception("The " + appBase + " does not exist!");

            File[] apps = appBasePath.listFiles();
            for (File app : apps) {
                if (app.isDirectory()) {
//                    System.out.println(app.getName() + " is an app");
                    // Load web.xml
                    this.loadAppConfig(app);
                }
            }
            System.out.println("Finished reading webapps dir");

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * parse the web.xml and make up  mapper <urlPattern, servletInstance>
     * @param appPath
     */
    private void loadAppConfig(File appPath) {
        String confUrl = appPath.getAbsolutePath().replaceAll("\\\\", "/") + "/web.xml";
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(confUrl);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(confUrl);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();

            List<Element> servlets = rootElement.selectNodes("//servlet");
            for (int i = 0; i < servlets.size(); i++) {
                Element app = servlets.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) app.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) app.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = "/" + appPath.getName() + servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
            System.out.println("Finished load config!");
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
